const app = getApp();

//单张图片上传
function uploadImage(file){
  return new Promise(function(resolve,reject){
    wx.uploadFile({
      url:app.api_root + '/index/upload_img',
      filePath:file,
      name:"file",
      header:{token:wx.getStorageSync('token')},
      formData:{},
      success(res){
        console.log("上传成功");
        let data=JSON.parse(res.data)
        console.log(data)
        resolve(data.data.path)
      },
      fail(res){
        reject(res);
        wx.showToast({
          title: '上传失败',
          icon:'none'
        })
        console.log("上传失败");
      }
    })
  })
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-')
}
// 增加一年
function formatTime1(date) {
  var year = date.getFullYear() + 1
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-')
}

function fommatetime(value) {           //将时间格式直接截取字符串获取年月日
  var year = value.substr(0, 4)
  var month = value.substr(5, 2)
  var day = value.substr(8, 2)
  var hour = value.substr(11, 2)
  var min = value.substr(14, 2)
  return year + "年" + month + "月" + day + "日"
  // return year+"-"+month+"-"+day
}


function formatNumber(n) {    //个位数时在前面补0
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 时间戳转化位日期格式
function timestampToTime(timestamp) {
  var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = date.getDate() + ' ';
  var h = date.getHours() + ':';
  var m = date.getMinutes() + ':';
  var s = date.getSeconds();
  return Y+"-"+M+"-"+D+" "+h+":"+m
}
module.exports = {
    /**
   * scene解码
   */
  scene_decode: function(e) {
    if (e === undefined)
      return {};
    let scene = decodeURIComponent(e),
      params = scene.split(','),
      data = {};
    for (let i in params) {
      var val = params[i].split(':');
      val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
    }
    return data;
  },
  uploadImage,
  fommatetime,
  formatTime,
  formatTime1,
  formatNumber,
  timestampToTime,
  subscribeMessage
}

function subscribeMessage(val){
  //需要订阅的消息模板，在微信公众平台手动配置获取模板ID
let message = val; // 模板id
// console.log(message)
//如果总是拒绝（subscriptionsSetting，2.10.1库才支持）
if(versionCompare('2.10.1')){
    wx.getSetting({
        withSubscriptions: true,//是否同时获取用户订阅消息的订阅状态，默认不获取
        success: (res)=> {
            console.log(res)
            if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
                res.subscriptionsSetting.itemSettings[message] == "reject"){
                //打开设置去设置
                openConfirm('检测到您没打开推送权限，是否去设置打开？');
            }else if(res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
              res.subscriptionsSetting.itemSettings[message] == "accept") { // 已有授权过
              console.log('已有订阅授权过')
            } else {
                wx.requestSubscribeMessage({
                    tmplIds: [message],
                    success: (res)=> {
                        if (res[message] == 'accept'){
                            //用户允许
                        }
                    },
                    fail: (res)=> { console.info(res) },
                })
            }
        }
    })
}else if(versionCompare('2.4.4')){
    wx.requestSubscribeMessage({
        tmplIds: [message],
        success: (res)=> {
            if (res[message] == 'accept'){
                //用户允许
            }
        },
        fail: (res)=> { console.info(res) },
    })
}
//打开设置
function openConfirm(message) {
wx.showModal({
  content: message,
  confirmText: "确认",
  cancelText: "取消",
  success: (res) => {
      //点击“确认”时打开设置页面
      if (res.confirm) {
          wx.openSetting({
              success: (res) => {
                  console.log(res.authSetting)
              },
              fail: (error) => {
                  console.log(error)
              }
          })
      } else {
          console.log('用户点击取消')
      }
  }
});
}
//基础库版本比较
function versionCompare(v) {
const version = wx.getSystemInfoSync().SDKVersion
if (compareVersion(version, v) >= 0) {
  return true
} else {
  return false
}
}
function compareVersion (v1, v2) {
v1 = v1.split('.')
v2 = v2.split('.')
var len = Math.max(v1.length, v2.length)

while (v1.length < len) {
v1.push('0')
}
while (v2.length < len) {
v2.push('0')
}

for (var i = 0; i < len; i++) {
var num1 = parseInt(v1[i])
var num2 = parseInt(v2[i])

if (num1 > num2) {
return 1
} else if (num1 < num2) {
return -1
}
}
return 0
}
}